package org.wit.ecommerce.service.impl;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.wit.ecommerce.dao.UserDao;
import org.wit.ecommerce.domain.ClientUser;
import org.wit.ecommerce.domain.PartnerUser;
import org.wit.ecommerce.domain.SuperUser;
import org.wit.ecommerce.domain.User;
import org.wit.ecommerce.dto.Navigator;
import org.wit.ecommerce.service.IUserService;
import org.wit.ecommerce.util.MD5;
import org.wit.ecommerce.util.PageNavigateCalculator;
/**
 * @spring.bean id="userService" parent="baseTransactionProxy" extends="true" transactionProxy="true"
 * @author Justin
 *
 */
public class UserServiceImpl implements IUserService {
	private UserDao userDao;
	@Override
	public void createUser(User user) {
		user.setCreateDate(new Timestamp(Calendar.getInstance().getTimeInMillis()));
		userDao.save(user);
	}

	@Override
	public void updateUser(User user) {
		userDao.save(user);
	}

	@Override
	public User changeUserStatus(Long id, int status) {
		User user = userDao.get(id);
		user.setStatus(status);
		userDao.save(user);
		return user;
	}

	@Override
	public User changeUserPassword(Long id, String password) {
		User user = userDao.get(id);
		user.setPassword(MD5.encrypt(password));
		userDao.save(user);
		return user;
	}

	@Override
	public void deleteUser(Long id) {
		userDao.delete(id);
	}

	@Override
	public void deleteUsers(Long[] ids) {
		userDao.batchDelete(ids);
	}

	@Override
	public Navigator<User> getUsersByPage(int page, Map<String, ?> keywords) {
		PageNavigateCalculator pnc = new PageNavigateCalculator();
		pnc.setCurrentPage(page);
		pnc.setTotalRowsAmount(userDao.getTotalCount(keywords));
		int start = pnc.getCurrentPageRows();
		int limit = pnc.getPageSize();
		
		List<User> users = userDao.findByPage(start, limit, keywords);
		Navigator<User> navigator = new Navigator<User>();
		navigator.setData(users);
		navigator.setNext(pnc.HasNext());
		navigator.setPageSize(pnc.getPageSize());
		navigator.setPrevious(pnc.HasPrevious());
		navigator.setTotalPages(pnc.getTotalPages());
		navigator.setTotalRowsAmount(pnc.getTotalRowsAmount());
		return navigator;
	}

	@Override
	public User login(String email, String password) {
		return userDao.findUser(email, MD5.encrypt(password));
	}

	@Override
	public User getUserById(Long id) {
		return userDao.get(id);
	}

	@Override
	public SuperUser getSuperById(Long id) {
		return userDao.getSuperById(id);
	}

	@Override
	public PartnerUser getPartnerById(Long id) {
		return userDao.getPartnerById(id);
	}

	@Override
	public ClientUser getClientById(Long id) {
		return userDao.getClientById(id);
	}
	/**
	 * @spring.property ref="userDao"
	 * @param userDao
	 */
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
}
